package com.abhimanyu.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class XoomDollarRateObserver implements ICurrencyRateObserver {

	String url = "https://www.xoom.com/india";
	private static final String PARSE_START = "1 USD = ";
	private static final String PARSE_END = "INR";

	public String getCurrentDollarRate() {
		String dollarRate = null;
		try {
			String webPageContent = getXoomWebPageForDollarRate();
			dollarRate = getDollarRate(webPageContent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dollarRate;
	}

	// HTTP GET request
	private String getXoomWebPageForDollarRate() throws Exception {

		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		// optional default is GET
		con.setRequestMethod("GET");
		con.setReadTimeout(0);
		// add request header
		// con.setRequestProperty("User-Agent", USER_AGENT);

		int responseCode = con.getResponseCode();
		System.out.println("\nSending 'GET' request to URL : " + url);
		System.out.println("Response Code : " + responseCode);

		BufferedReader in = new BufferedReader(new InputStreamReader(
				con.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();

		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();

		// print result
		System.out.println(response.toString());

		return response.toString();
	}

	private String getDollarRate(String webPageContent) {
		return webPageContent.substring(webPageContent.indexOf(PARSE_START)
				+ PARSE_START.length(), webPageContent.indexOf(PARSE_END));
	}

	public static void main(String[] args) {
		System.out.println(new XoomDollarRateObserver().getCurrentDollarRate());
	}
	
	@Override
	public String toString() {
		return "Xoom's rate";
	}
}
